package com.xx.baogao.dame;

import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SampleTransferFormFiller {
    public static void main(String[] args) {
        // 模板文件和输出文件路径
        String templatePath = "E:\\word\\所有附件：lims实验室\\样品检测流转单.docx";
        String outputPath = "E:\\word\\所有附件：lims实验室\\已填充的样品检测流转单.docx";

        // 1. 准备静态假数据（表格上方的固定信息）
        Map<String, String> staticData = new HashMap<>();
        staticData.put("projectNo", "JC202408004");
        staticData.put("sampleManager", "张伟");
        staticData.put("entrustingUnit", "XX环境监测站");
        staticData.put("handoverDate", "2024-08-05");
        staticData.put("sampleCheck", "所有样品包装完好，标识清晰，符合检测要求");
        staticData.put("deadlineDate", "2024-08-25");
        staticData.put("subsamplingTime", "2024-08-05 15:30");

        // 2. 准备多列多行假数据（表格中的样品列表）
        List<Map<String, String>> sampleList = new ArrayList<>();

        // 第一行样品数据
        Map<String, String> sample1 = new HashMap<>();
        sample1.put("testType", "常规检测");
        sample1.put("sampleNo", "YP202408004-001");
        sample1.put("testItem", "pH值、溶解氧、浊度");
        sample1.put("quantity", "3份");
        sample1.put("storageCondition", "常温保存");
        sample1.put("samplingTime", "2024-08-04 08:15");
        sample1.put("analyst", "刘敏");
        sample1.put("testStandard", "GB/T 5750.4-2023");
        sample1.put("sampleDisposal", "检测后保存3个月");
        sampleList.add(sample1);

        // 第二行样品数据
        Map<String, String> sample2 = new HashMap<>();
        sample2.put("testType", "专项检测");
        sample2.put("sampleNo", "YP202408004-002");
        sample2.put("testItem", "重金属（铅、镉、汞）");
        sample2.put("quantity", "5份");
        sample2.put("storageCondition", "4℃冷藏");
        sample2.put("samplingTime", "2024-08-04 09:30");
        sample2.put("analyst", "王强");
        sample2.put("testStandard", "HJ 700-2014");
        sample2.put("sampleDisposal", "检测后按危废处理");
        sampleList.add(sample2);

        // 第三行样品数据
        Map<String, String> sample3 = new HashMap<>();
        sample3.put("testType", "应急检测");
        sample3.put("sampleNo", "YP202408004-003");
        sample3.put("testItem", "挥发酚、氰化物");
        sample3.put("quantity", "2份");
        sample3.put("storageCondition", "避光冷藏");
        sample3.put("samplingTime", "2024-08-04 14:20");
        sample3.put("analyst", "赵敏");
        sample3.put("testStandard", "HJ 503-2009");
        sample3.put("sampleDisposal", "检测后立即销毁");
        sampleList.add(sample3);

        try (
                FileInputStream fis = new FileInputStream(templatePath);
                XWPFDocument doc = new XWPFDocument(fis);
                FileOutputStream fos = new FileOutputStream(outputPath)
        ) {
            // 获取文档中的主表格
            XWPFTable table = doc.getTables().get(0);

            // 3. 填充静态数据（表格上方的固定信息）
            fillStaticData(table, staticData);

            // 4. 填充多列多行数据（样品列表）
            fillSampleTable(table, sampleList);

            // 写入输出文件
            doc.write(fos);
            System.out.println("多行多列数据填充完成，文件保存至：" + outputPath);

        } catch (IOException e) {
            System.err.println("填充失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 填充表格中的静态数据（非列表部分）
     */
    private static void fillStaticData(XWPFTable table, Map<String, String> data) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                for (XWPFParagraph para : cell.getParagraphs()) {
                    replacePlaceholders(para, data);
                }
            }
        }
    }

    /**
     * 填充多列多行的样品数据
     * 假设模板中已有一行样品数据作为模板行，我们在其下方插入新行
     */
    private static void fillSampleTable(XWPFTable table, List<Map<String, String>> sampleList) {
        // 找到样品数据的模板行（假设是表格中的第5行，索引从0开始）
        int templateRowIndex = 4; // 根据实际模板调整
        XWPFTableRow templateRow = table.getRow(templateRowIndex);

        // 先删除模板行的原始内容（占位符）
        replacePlaceholdersInRow(templateRow, sampleList.get(0));

        // 为剩余的样品数据创建新行并填充
        for (int i = 1; i < sampleList.size(); i++) {
            // 复制模板行的结构（包括列宽、样式）
            XWPFTableRow newRow = table.insertNewTableRow(templateRowIndex + i);
            copyRowStyle(templateRow, newRow);

            // 填充当前行的数据
            replacePlaceholdersInRow(newRow, sampleList.get(i));
        }
    }

    /**
     * 复制行样式（列宽、单元格样式）
     */
    private static void copyRowStyle(XWPFTableRow sourceRow, XWPFTableRow targetRow) {
        // 复制列数和列宽
        targetRow.getTableCells().clear();
        for (XWPFTableCell sourceCell : sourceRow.getTableCells()) {
            XWPFTableCell newCell = targetRow.addNewTableCell();
            // 修正：将宽度转换为字符串
            newCell.setWidth(String.valueOf(sourceCell.getWidth()));
            // 复制单元格内的段落结构
            for (XWPFParagraph sourcePara : sourceCell.getParagraphs()) {
                XWPFParagraph newPara = newCell.addParagraph();
                newPara.getCTP().set(sourcePara.getCTP());
            }
        }
    }

    /**
     * 替换一行中所有单元格的占位符
     */
    private static void replacePlaceholdersInRow(XWPFTableRow row, Map<String, String> data) {
        for (XWPFTableCell cell : row.getTableCells()) {
            for (XWPFParagraph para : cell.getParagraphs()) {
                replacePlaceholders(para, data);
            }
        }
    }

    /**
     * 替换段落中的占位符
     */
    private static void replacePlaceholders(XWPFParagraph para, Map<String, String> data) {
        // 拼接原有文本
        StringBuilder originalText = new StringBuilder();
        for (XWPFRun run : para.getRuns()) {
            String runText = run.getText(0);
            if (runText != null) {
                originalText.append(runText);
            }
        }

        // 替换占位符
        String replacedText = originalText.toString();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String placeholder = "${" + entry.getKey() + "}";
            replacedText = replacedText.replace(placeholder, entry.getValue());
        }

        // 清空原有内容
        while (para.getRuns().size() > 0) {
            para.removeRun(0);
        }

        // 添加替换后的文本
        XWPFRun newRun = para.createRun();
        newRun.setText(replacedText);
    }
}
    